package cn.com.my.gallery;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter4.BaseQuickAdapter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.util.ArrayList;
import java.util.List;

import cn.com.my.gallery.utils.ImageDatabaseHelper;

public class ImageActivity extends AppCompatActivity {
    private static final String TAG = "ImageActivity";
    private ImageAdapter adapter;
    private RecyclerView rvList;
    int spanCount = 3; // 4列
    int spacing = 10; // 10dp间距
    private List<ImageBean> imagesAll = new ArrayList<>();
    private List<ImageBean> imagesTemp = new ArrayList<>();
    private EditText etName;
    private Button btnSearch;
    private FloatingActionButton floatAdd;
    private ImageDatabaseHelper imageDatabaseHelper;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_img);
        adapter = new ImageAdapter(imagesTemp);
        rvList = findViewById(R.id.rvPhoto);
        etName = findViewById(R.id.etName);
        btnSearch = findViewById(R.id.btnSearch);
        floatAdd = findViewById(R.id.floatAdd);
        imageDatabaseHelper = new ImageDatabaseHelper(this);
        boolean includeEdge = true; // 包含边缘
        rvList.setLayoutManager(new GridLayoutManager(this, spanCount));
        rvList.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
        rvList.setAdapter(adapter);
        imagesAll.addAll(imagesAll);
        imagesTemp.addAll(imagesAll);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener<ImageBean>() {
            @Override
            public void onClick(@NonNull BaseQuickAdapter<ImageBean, ?> baseQuickAdapter, @NonNull View view, int i) {
                ImageBean imageFolderBean = adapter.getItem(i);
                Intent intent = new Intent(ImageActivity.this, ImageViewActivity.class);
                intent.putExtra("path", imageFolderBean.data);
                startActivity(intent);

            }
        });
        floatAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addImages();
            }
        });
        adapter.notifyDataSetChanged();

        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String keyName = etName.getText().toString();
                search(keyName);

            }
        });
        etName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                search(editable.toString());
            }
        });
        loadAllImages();
    }

    private void addImages() {
        PictureSelector.create(this)
                .openSystemGallery(SelectMimeType.ofImage())
                .setSelectionMode(SelectModeConfig.SINGLE)
                .forSystemResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        Log.d(TAG, "onResult: "+result);
                        if(!result.isEmpty()){
                            LocalMedia media = result.get(0);
                            ImageBean imageBean = new ImageBean();
                            imageBean.name = media.getFileName();
                            imageBean.bucket = media.getParentFolderName();
                            imageBean.data = media.getRealPath();
                            imageBean.size = (int) media.getSize();
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    imageDatabaseHelper.insertImage(imageBean);
                                    loadAllImages();
                                }
                            }).start();

                        }

                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    private void loadAllImages() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                imagesAll.clear();
                imagesTemp.clear();
                imagesAll.addAll(imageDatabaseHelper.getAllImages());
                imagesTemp.addAll(imagesAll);
                rvList.post(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();

    }


    private void search(String keyName) {
        imagesTemp.clear();
        for (ImageBean imageFolderBean : imagesAll) {
            if (imageFolderBean.data.toLowerCase().contains(keyName.toLowerCase())) {
                imagesTemp.add(imageFolderBean);
            }
        }
        adapter.notifyDataSetChanged();
    }


}
